<template>
  <a-modal
    :title="title"
    :width="modalWidth"
    :visible="visible"
    :confirmLoading="confirmLoading"
    @ok="handleOk"
    @cancel="handleCancel"
    :okText="$t('保存')"
    :cancelText="$t('关闭')"
  >
    <a-spin :spinning="confirmLoading">
      <a-form :form="form">
        <a-form-item :labelCol="labelCol" :wrapperCol="wrapperCol" :label="$t('旧密码')">
          <a-input
            type="password"
            :placeholder="$t('请输入旧密码')"
            v-decorator="['oldpassword', validatorRules.oldpassword]"
          />
        </a-form-item>

        <a-form-item :labelCol="labelCol" :wrapperCol="wrapperCol" :label="$t('新密码')">
          <div style="display: flex; align-items: center; height: 40px">
            <a-input
              type="password"
              :placeholder="$t('请输入新密码')"
              v-decorator="['password', validatorRules.password]"
            /><!-- <span
              v-if="!freePass"
              style="color: #1890ff; white-space: nowrap; margin-left: 4px"
              @click="closeValid"
              >{{ $t('关闭安全密码') }}</span
            > -->
          </div>
        </a-form-item>

        <a-form-item :labelCol="labelCol" :wrapperCol="wrapperCol" :label="$t('确认密码')">
          <a-input
            type="password"
            @blur="handleConfirmBlur"
            :placeholder="$t('请确认新密码')"
            v-decorator="['confirmpassword', validatorRules.confirmpassword]"
          />
        </a-form-item>
      </a-form>
    </a-spin>
    <user-settings-modal ref="modalForm" @close="modalFormOk" />
  </a-modal>
</template>

<script>
import { putAction } from '@/api/manage'
import UserSettingsModal from '@/views/system/modules/UserSettingsModal'

export default {
  name: 'UserPassword',
  components: {
    UserSettingsModal,
  },
  data() {
    return {
      title: this.$t('修改密码'),
      modalWidth: 800,
      visible: false,
      confirmLoading: false,
      validatorRules: {
        oldpassword: { rules: [{ required: true, message: this.$t('请输入旧密码') }] },
        password: {
          rules: [{ required: true, message: this.$t('请输入新密码') }, { validator: this.validateToNextPassword }],
        },
        confirmpassword: {
          rules: [{ required: true, message: this.$t('请确认新密码') }, { validator: this.compareToFirstPassword }],
        },
      },
      confirmDirty: false,
      labelCol: {
        xs: { span: 24 },
        sm: { span: 5 },
      },
      wrapperCol: {
        xs: { span: 24 },
        sm: { span: 16 },
      },

      form: this.$form.createForm(this),
      url: 'sys/user/updatePassword',
      username: '',
      freePass: localStorage.getItem('freePass') == 'true' ? true : false,
    }
  },
  methods: {
    closeValid() {
      this.$refs.modalForm.show()
    },
    modalFormOk() {
      this.$nextTick(() => {
        this.freePass = localStorage.getItem('freePass') == 'true' ? true : false
        this.form.validateFields(['password'], { force: true })
      })
    },
    show(uname) {
      if (!uname) {
        this.$message.warning(this.$t('当前系统无登录用户'))
        return
      } else {
        this.username = uname
        this.freePass = localStorage.getItem('freePass') == 'true' ? true : false
        this.form.resetFields()
        this.visible = true
      }
    },
    handleCancel() {
      this.close()
    },
    close() {
      this.$emit('close')
      this.visible = false
      this.disableSubmit = false
      this.selectedRole = []
    },
    handleOk() {
      let that = this
      // 触发表单验证
      that.form.validateFields((err, values) => {
        if (!err) {
          that.confirmLoading = true
          let params = Object.assign({ username: that.username }, values)
          putAction(that.url, params)
            .then((res) => {
              if (res.success) {
                that.$message.success(res.message)
                that.close()
              } else {
                that.$message.warning(res.message)
              }
            })
            .finally(() => {
              that.confirmLoading = false
            })
        }
      })
    },
    validateToNextPassword(rule, value, callback) {
      const form = this.form
      const confirmpassword = form.getFieldValue('confirmpassword')
      if (value && confirmpassword && value !== confirmpassword) {
        callback(this.$t('两次输入的密码不一样'))
      }
      if (!this.freePass) {
        if (!/^(?=.*[a-zA-Z])(?=.*\d)(?=.*[~!@#$%^&*()_+`\-={}:";'<>?,./]).{8,20}$/.test(value)) {
          callback(this.$t('密码由8~20位数字、大小写字母和特殊符号组成!'))
        }
      }
      if (value && this.confirmDirty) {
        form.validateFields(['confirm'], { force: true })
      }
      callback()
    },
    compareToFirstPassword(rule, value, callback) {
      const form = this.form
      if (value && value !== form.getFieldValue('password')) {
        callback(this.$t('两次输入的密码不一样'))
      } else {
        callback()
      }
    },
    handleConfirmBlur(e) {
      const value = e.target.value
      this.confirmDirty = this.confirmDirty || !!value
    },
  },
}
</script>

<style scoped>
</style>

